package com.bawei.module_mine.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_storage.room.entity.FavoriteEntity
import com.bawei.module_mine.R
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

class FavoriteAdapter : RecyclerView.Adapter<FavoriteAdapter.FavoriteViewHolder>() {

    private val data = arrayListOf<FavoriteEntity>()
    
    // 点击事件接口
    var onItemClickListener: ((FavoriteEntity) -> Unit)? = null
    
    // 取消收藏事件接口
    var onUnfavoriteClickListener: ((FavoriteEntity) -> Unit)? = null

    fun setData(newData: List<FavoriteEntity>) {
        data.clear()
        data.addAll(newData)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoriteViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_favorite, parent, false)
        return FavoriteViewHolder(view)
    }

    override fun onBindViewHolder(holder: FavoriteViewHolder, position: Int) {
        val item = data[position]
        
        holder.tvTitle.text = item.title
        holder.tvAuthor.text = item.authorName
        holder.tvContent.text = item.content
        
        // 加载封面图片
        Glide.with(holder.itemView.context)
            .load(item.primaryImg)
            .transform(CenterCrop(), RoundedCorners(8))
            .into(holder.ivCover)
            
        // 加载作者头像
        Glide.with(holder.itemView.context)
            .load(item.authorImg)
            .into(holder.ivAuthor)
            
        // 添加点击事件
        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(item)
        }
        
        // 添加取消收藏点击事件
        holder.ivUnfavorite.setOnClickListener {
            onUnfavoriteClickListener?.invoke(item)
        }
    }

    override fun getItemCount(): Int = data.size

    inner class FavoriteViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val ivCover: ImageView = view.findViewById(R.id.iv_cover)
        val ivAuthor: ImageView = view.findViewById(R.id.iv_author)
        val ivUnfavorite: ImageView = view.findViewById(R.id.iv_unfavorite)
        val tvTitle: TextView = view.findViewById(R.id.tv_title)
        val tvAuthor: TextView = view.findViewById(R.id.tv_author)
        val tvContent: TextView = view.findViewById(R.id.tv_content)
    }
} 